package com.zhongxi.guoyuan.fragment.beanexchange;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinPost.LogisiticsInfoAdapter;
import com.zhongxi.guoyuan.adapter.personExchangeOrder.PersonExchangeNoEvaluateAdapter;
import com.zhongxi.guoyuan.adapter.personExchangeOrder.PersonExchangeNoPayAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.PersonExchangeResult;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsData;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.beanExchange.PersonExchangeActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedDetailActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class ExchangeNoEvaluateFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView>, View.OnClickListener {

    @Bind(R.id.pullToRefreshListView)
    PullToRefreshListView mPullToRefreshListView;


    private PersonExchangeNoEvaluateAdapter mNoPayAdapter;


    private List<PersonExchangeResult.OrderInfo> mInfoList = new ArrayList<>();
    private String post;
    private String shopInfo;
    private PersonExchangeResult personExchangeResult;
    private String type;
    private int position;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            position=msg.getData().getInt("pos");
            switch (msg.what){
                case 1://评价
                   showEvaluateDialog();
                    break;
                case 2://投诉
                    showCommentWindow();
                    break;
                case 3://看物流
                    getLogisitics();
                    break;
            }
        }
    };
    private String content;
    private LogisiticsInfoAdapter infoAdapter;
    private android.app.AlertDialog dialog;
    private EditText editText;
    private int score;
    private String evaluateContent;

    public ExchangeNoEvaluateFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View mInflate = inflater.inflate(R.layout.fragment_exchange_no_pay, container, false);
        ButterKnife.bind(this,mInflate);
        return mInflate;
    }

    @Override
    protected void initView() {
        super.initView();
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshListView.setOnRefreshListener(this);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            getData();
    }

    @Override
    protected void initData() {
        super.initData();
        mNoPayAdapter = new PersonExchangeNoEvaluateAdapter(mHandler, getContext());
        mPullToRefreshListView.setAdapter(mNoPayAdapter);
        getData();
    }

    public void getData() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.EXCHANGE_NOEVALUATE, null, str, false, null, "get");
    }
    Map<String,String> map=new HashMap<>();
    /***
     * 投诉
     */
    private void goComplaints(String content) {
        type="complaints";
        map.clear();
        map.put("ordertype",mInfoList.get(position).getOrdertype());
        map.put("orderid",mInfoList.get(position).getId());
        map.put("shopid",mInfoList.get(position).getShopid());
        map.put("content",content);
        for (String mmap:map.keySet()) {
            Log.d("flag", mmap+" : "+map.get(mmap));
        }
        getServer(Url.EXCHANGE_COMFLAINTSORDER, map, "", false, null, "post");
    }
    /***
     * 查物流
     */
    private void getLogisitics(){
        type = "logistics";
        map.clear();
        map.put("orderid", mInfoList.get(position).getId());

        getServer(Url.EXCHANGE_LOGISITICSINFO, map, "", false, null, "post");
    }
    /**
     * 添加评价
     */
    private void toEvaluate() {
        type = "addevaluate";
        Map<String, String> map = new HashMap<>();
        map.put("shopid", mInfoList.get(position).getShopid());
        map.put("orderid", mInfoList.get(position).getId());
        map.put("goodsid", mInfoList.get(position).getGoodsid());
        map.put("starlevel", score + "");
        map.put("content", evaluateContent);
        Set<Map.Entry<String, String>> mEntries = map.entrySet();
        for (Map.Entry<String,String> mnt:mEntries) {
            Log.d("flag", "key: "+mnt.getKey()+":"+mnt.getValue());
        }

        getServer(Url.EXCHANGE_ADDCOMMENT, map, "", false, null, "post");
    }

    /**
     * 去投诉
     */
    private void showCommentWindow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_to_complaint, null);
        final EditText editText = (EditText) view.findViewById(R.id.etTips_fuwu);
        final TextView textView = (TextView) view.findViewById(R.id.tvNum_fuwu);
        TextView submit = (TextView) view.findViewById(R.id.tv_submit_complaint);
        ImageView cancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        builder.setView(view);
        final AlertDialog dialog = builder.create();

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(context, textView, editable, 150);
            }
        });


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                content = editText.getText().toString().trim();

                if (null != content && !"".equals(content)) {
                    goComplaints(content);
                    dialog.dismiss();
                } else {
                    showShortToast("请输入您的意见！");
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    /***
     * 评价
     */
    private void showEvaluateDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(context).inflate(R.layout.clearweed_evaluate, null);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCancelable(false);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        ImageView ivCancel = (ImageView) view.findViewById(R.id.dialog_evaluate_cancel);
        editText = (EditText) view.findViewById(R.id.dialog_evaluate_content);
        final TextView textNum = (TextView) view.findViewById(R.id.dialog_evaluate_textNum);
        TextView payCanael = (TextView) view.findViewById(R.id.dialog_evaluate_paycancel);
        TextView paySure = (TextView) view.findViewById(R.id.dialog_evaluate_paysure);
        RatingBar ratingBar = (RatingBar) view.findViewById(R.id.dialog_evaluate_ratingBar);

        ivCancel.setOnClickListener(this);
        payCanael.setOnClickListener(this);
        paySure.setOnClickListener(this);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(getContext(), textNum, editable, 200);
            }
        });

        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                score = (int) ratingBar.getRating();
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_evaluate_cancel:
                if (dialog != null) {
                    dialog.dismiss();
                }
                break;
            case R.id.dialog_evaluate_paycancel:
                editText.setText("");
                break;
            case R.id.dialog_evaluate_paysure:
                evaluateContent = editText.getText().toString().trim();
                if (score < 1) {
                    showShortToast("请选择您的评分");
                } else if (evaluateContent.equals("") || evaluateContent.length() < 1) {
                    showShortToast("请输入您的评价");
                } else {
                    toEvaluate();
                }

                break;
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson mGson = new Gson();
        if (type.equals("order")){
            personExchangeResult = mGson.fromJson(response, PersonExchangeResult.class);
            MyApplication.getInstance().setSpValue(personExchangeResult.getSafeobj());
            if (personExchangeResult.getCode() == 1) {
                if (mPullToRefreshListView.isRefreshing())
                    mPullToRefreshListView.onRefreshComplete();

                if (pageNum == 1) {
                    mInfoList.clear();
                }

                if (personExchangeResult.getOrderInfo().size()>0){
                    mInfoList.addAll(personExchangeResult.getOrderInfo());
                }else {
                    if (pageNum!=1)
                        pageNum--;
                }

                try {
                    JSONObject mJSONObject=new JSONObject(response);
                    post=mJSONObject.optString("post");
                    shopInfo=mJSONObject.optString("shopInfo");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mNoPayAdapter.setData(mInfoList, post, shopInfo, (PersonExchangeActivity) getActivity());
                mNoPayAdapter.notifyDataSetChanged();
            }
        }else if (type.equals("logistics")){
            LogisiticsResult result = mGson.fromJson(response, LogisiticsResult.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            LogisiticsData logisitics = result.getData();
            showLogisticsInfo(logisitics);
        }else if (type.equals("complaints")){
            BaseResponse mBaseResponse=mGson.fromJson(response,BaseResponse.class);
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
            showShortToast("投诉成功");
        }else if (type.equals("addevaluate")){
            BaseResponse mBaseResponse=mGson.fromJson(response,BaseResponse.class);
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
            showShortToast("评价成功");
            if (dialog!=null&&dialog.isShowing()){
                dialog.dismiss();
            }
            getData();

        }
    }

    /**
     * 物流时间轴
     */
    private void showLogisticsInfo(LogisiticsData logisitics) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.post_show_logisitics, null);
        ImageView back = (ImageView) view.findViewById(R.id.post_logisitics_back);
        TextView company = (TextView) view.findViewById(R.id.post_logisitics_company);
        TextView number = (TextView) view.findViewById(R.id.post_logisitics_number);
        ListView list = (ListView) view.findViewById(R.id.post_logisitics_list);
        TextView error = (TextView) view.findViewById(R.id.logisitics_error);
        builder.setView(view);

        final AlertDialog dialog = builder.create();

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        if (!logisitics.getState().equals("4")) {
            company.setText("快递公司:" + logisitics.getShipper());
            number.setText("运单编号:" + logisitics.getLogisticCode());
            infoAdapter = new LogisiticsInfoAdapter(getContext());
            list.setAdapter(infoAdapter);
            List<LogisiticsData.Traces> traces = logisitics.getTraces();
            Collections.reverse(traces);
            infoAdapter.setList(traces);
        } else {
            list.setVisibility(View.GONE);
            error.setVisibility(View.VISIBLE);
        }
        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display defaultDisplay = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
        attributes.height = (int) (defaultDisplay.getHeight() * 0.7);
        dialog.getWindow().setAttributes(attributes);
    }
    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson=new Gson();
        BaseResponse mBaseResponse=gson.fromJson(response,BaseResponse.class);
        if(null!=mBaseResponse.getSafeobj()&&!"".equals(mBaseResponse.getSafeobj())){
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
        }

        Log.d("flag", "ProcessFailResult: "+mBaseResponse.getCode());
        if (mBaseResponse.getCode()==1558){
            showShortToast("您已投诉，不可重复投诉");
        }
        if (mBaseResponse.getCode()==2016){
            showShortToast("订单信息丢失");
        }
        if (mBaseResponse.getCode()==1559){
            showShortToast("您已评价过了，不可重复评价");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getData();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getData();
    }


}
